<template>
  <view class="analysis-result-container">
    <!-- 使用系统导航栏，移除自定义头部 -->
    
    <view class="main-content">
      <view class="result-card">
        <view class="card-header">
          <text class="header-title">🎨 AI艺术解读</text>
        </view>
        
        <view class="result-content">
          <view class="analysis-section">
            <view class="section-header">
              <text class="section-title">💡 作品解读</text>
              <button class="copy-btn-small" @click="copyAnswer">复制</button>
            </view>
            <text class="content-text">{{ analysisResult.interpretation }}</text>
          </view>
        </view>
      </view>

      <!-- 状态提示 -->
      <view class="status-hint" v-if="isContinuing">分析中...</view>

             <view class="continue-analysis-section">
         <view class="section-title">基于同简介继续分析</view>
         <view class="upload-box" @click="pickImageForContinue" :class="{ 'uploading': isContinuing }">
           <image v-if="continueImage" :src="continueImage" class="preview" mode="aspectFit" />
           <view v-else class="placeholder">
             <image 
               :src="PRESET_EXHIBITION_2.url" 
               class="preset-preview" 
               mode="aspectFit"
               @error="onPresetImageError"
               @load="onPresetImageLoad"
             />
             <text class="hint">点击上传新作品图片</text>
             <text class="sub">可使用预设图片</text>
           </view>
         </view>
         <button class="continue-btn" :disabled="isContinuing" @click="continueWithSameContext">
           {{ isContinuing ? '分析中...' : '开始分析' }}
         </button>
       </view>

      <view class="action-buttons">
        <button class="action-btn back-btn" @click="goBackToUpload">返回上传页</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { difyUploadFile, difyCreateChatMessage } from '@/services/api/backendApi'

const analysisResult = ref({
  artStyle: '',
  interpretation: '',
  historicalContext: ''
});

// 第三张预设图片数据（新接口直接使用URL，不需要upload_file_id）
const PRESET_EXHIBITION_2 = { 
  url: 'https://douyin-ai.tos-cn-shanghai.volces.com/context3.jpg' 
}

let contextImageUrl = ''
let conversationId = ''  // 保存第一次分析返回的conversation_id
let userId = ''
const isContinuing = ref(false)
const continueImage = ref('')

onMounted(() => {
  const pages = getCurrentPages();
  const current = pages[pages.length - 1];
  const { options } = current;
  const answer = options?.answer ? decodeURIComponent(options.answer) : '';
  contextImageUrl = options?.contextImageUrl ? decodeURIComponent(options.contextImageUrl) : ''
  conversationId = options?.conversationId ? decodeURIComponent(options.conversationId) : ''  // 获取conversation_id
  userId = String(uni.getStorageSync('userId') || 1)
  analysisResult.value = {
    artStyle: '',
    interpretation: answer || '正在生成解读...',
    historicalContext: ''
  };
  
  // 调试：检查预设图片URL
  console.log('预设图片URL:', PRESET_EXHIBITION_2.url);
  console.log('conversationId:', conversationId);
  console.log('contextImageUrl:', contextImageUrl);
});

function pickImageForContinue() {
  if (isContinuing.value) return
  
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const filePath = res.tempFilePath || res.tempFilePaths?.[0]
      if (!filePath) return
      continueImage.value = filePath
    }
  })
}

// 预设图片加载成功
function onPresetImageLoad() {
  console.log('预设图片加载成功，URL:', PRESET_EXHIBITION_2.url);
  console.log('预设图片元素:', document.querySelector('.preset-preview'));
}

// 预设图片加载失败
function onPresetImageError(e) {
  console.error('预设图片加载失败，URL:', PRESET_EXHIBITION_2.url);
  console.error('错误详情:', e);
  uni.showToast({
    title: '预设图片加载失败',
    icon: 'none'
  });
}

async function continueWithSameContext() {
  try {
    if (!conversationId) {
      uni.showToast({ title: '缺少对话ID，请返回重新分析', icon: 'none' })
      return
    }
    
    isContinuing.value = true
    
    let exhibitionImageUrl
    
    if (continueImage.value) {
      // 用户上传了新图片，使用新图片的URL
      console.log('用户上传了新图片，使用新图片URL...')
      exhibitionImageUrl = continueImage.value
      console.log('使用新作品图片URL:', exhibitionImageUrl)
    } else {
      // 用户没有上传新图片，使用预设图片的URL
      console.log('用户未上传新图片，使用预设图片URL...')
      exhibitionImageUrl = PRESET_EXHIBITION_2.url
      console.log('使用预设示例图2 URL:', exhibitionImageUrl)
    }
    
    // 继续对话（使用conversation_id，use_context设为false）
    console.log('开始调用Dify API进行继续分析...')
    console.log('继续分析参数:', {
      exhibitionImageUrl: exhibitionImageUrl,
      userId,
      useContext: false,  // 继续分析时设为false
      conversationId: conversationId,
      contextImageUrl: null // 明确不传contextImageUrl，避免重复上传简介图片
    })
    const resp = await difyCreateChatMessage({
      exhibitionImageUrl: exhibitionImageUrl,
      userId,
      useContext: false,  // 继续分析时设为false
      conversationId: conversationId  // 使用第一次的conversation_id
      // 不传contextImageUrl，让Dify使用已有的conversation_id中的context
    })
    
    console.log('继续分析成功:', resp)
    analysisResult.value.interpretation = resp.answer || '（无返回内容）'
    uni.showToast({ title: '分析完成', icon: 'success' })
  } catch (e) {
    console.error('继续分析失败:', e)
    
    // 根据错误类型显示不同的提示
    let errorMessage = '继续分析失败，请重试'
    if (e.message && e.message.includes('网络连接问题')) {
      errorMessage = '网络连接不稳定，请检查网络后重试'
    } else if (e.message && e.message.includes('HTTP/2 stream')) {
      errorMessage = '网络连接中断，请重试'
    } else if (e.message && e.message.includes('预设图片上传失败')) {
      errorMessage = '预设图片上传失败，请手动上传图片'
    }
    
    uni.showToast({ 
      title: errorMessage, 
      icon: 'none',
      duration: 3000
    })
  } finally {
    isContinuing.value = false
  }
}

function copyAnswer() {
  const text = analysisResult.value.interpretation || ''
  if (!text) { uni.showToast({ title: '暂无可复制内容', icon: 'none' }); return }
  uni.setClipboardData({
    data: text,
    success: () => uni.showToast({ title: '已复制', icon: 'success' }),
    fail: () => uni.showToast({ title: '复制失败', icon: 'none' })
  })
}

function goBackToUpload() {
  uni.navigateBack({ delta: 1 })
}

function shareResult() {
  uni.showToast({
    title: '分享功能开发中',
    icon: 'none'
  });
}

function saveResult() {
  uni.showToast({
    title: '分析结果已保存',
    icon: 'success'
  });
}

function newAnalysis() {
  uni.navigateBack({
    delta: 2
  });
}
</script>

<style lang="scss">
.analysis-result-container {
  min-height: 100vh;
  background: #1a1a1a;
  padding-bottom: 40px;
}

/* 移除自定义头部样式（.header/.back-btn/.back-icon/.title） */

.main-content { padding: 20px; }

.result-card { background: rgba(255, 255, 255, 0.9); border-radius: 20px; padding: 25px; margin-bottom: 18px; }
.card-header { margin-bottom: 18px; padding-bottom: 12px; border-bottom: 1px solid rgba(255, 0, 80, 0.2); }
.header-title { font-size: 22px; font-weight: 600; color: #ff0050; }

.analysis-section { margin-bottom: 16px; }
.section-header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
  margin-bottom: 10px; 
}
.section-title { display: block; font-size: 16px; font-weight: 600; color: #ff0050; }
.content-text { display: block; font-size: 14px; line-height: 1.6; color: #000000; background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(245, 242, 237, 0.8)); border-radius: 12px; padding: 15px; border-left: 4px solid #ff0050; box-shadow: 0 2px 8px rgba(255, 0, 80, 0.15); }

.copy-btn-small {
  background: #ff0050;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  padding: 4px 8px;
  font-size: 11px;
  font-weight: 500;
  min-width: 32px;
  height: 20px;
  line-height: 12px;
  transition: all 0.3s ease;
  margin-right: -8px;
  
  &:active {
    transform: scale(0.95);
    background: #cc0040;
  }
}

.status-hint { text-align: center; color: #ffffff; font-size: 13px; margin: 6px 0 10px; }

.action-buttons { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; justify-items: center; }
.action-btn { background: #ff0050; border: none; color: #ffffff; font-weight: 600; }
.continue-btn { border-radius: 12px; padding: 10px 12px; font-size: 13px; min-width: 110px; }
.back-btn { border-radius: 12px; padding: 10px 12px; font-size: 13px; min-width: 100px; }

.btn-two-line { white-space: pre-line; line-height: 1.1; text-align: center; display: inline-block; }

.continue-analysis-section {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
}

.continue-analysis-section .section-title {
  font-size: 16px;
  font-weight: 600;
  color: #ff0050;
  margin-bottom: 15px;
  text-align: center;
}

.upload-box {
  height: 180px;
  border: 2px dashed rgba(255, 0, 80, 0.5);
  border-radius: 12px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(245, 242, 237, 0.85));
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-box.uploading {
  opacity: 0.6;
  pointer-events: none;
}

.placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #ff0050;
}

.plus {
  font-size: 28px;
  line-height: 1;
  margin-bottom: 6px;
}

.hint {
  font-size: 14px;
  font-weight: 600;
}

.sub {
  font-size: 12px;
  color: #ff0050;
  margin-top: 2px;
}

.preview { width: 100%; height: 100%; object-fit: contain; }

.preset-preview {
  width: 120px;
  height: 90px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 8px;
  display: block;
  border: 1px solid rgba(255, 0, 80, 0.3);
}

.continue-btn {
  background: #ff0050;
  color: #ffffff;
  border: none;
  border-radius: 25px;
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 600;
  width: 100%;
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2px);
    box-shadow: 0 2px 8px rgba(255, 0, 80, 0.3);
  }
}
</style>
